﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PessModel;
using PessMvc.Helpers;
using System.Web.Security;
using PessMvc.Models;

namespace PessMvc.Controllers
{
    [Authorize]
    public class ActivityController : Controller
    {
        private PESSEntities db = new PESSEntities();

        //
        // GET: /Activity/

        public ActionResult Index(string pessTypeID="")
        {
            HttpContext.Session.Add("ActivityID", -1);
            var activities = db.Activities.Include(a => a.PessType);
            
            if (pessTypeID.Trim() != "")
            {
                int pessTypeID1 = Convert.ToInt32(pessTypeID);
                activities=activities.Where(a => a.TypeID == pessTypeID1);
            }
            
            string userName=Membership.GetUser().UserName;
            if (Roles.IsUserInRole(Membership.GetUser().UserName, "CountyAdmin"))
            {
                activities = activities.Where(a =>
                    (ActivityStatus)a.Status == ActivityStatus.Open
                    || (ActivityStatus)a.Status == ActivityStatus.Done);
            }

            if (Roles.IsUserInRole(Membership.GetUser().UserName, "ExpertJudge"))
            {
                //int activityID = db.ExpertJudges.Find(userName).ExpertGroup.Subject.ActivityID;
                var activityID = db.ExpertJudges.Find(userName).ExpertGroups.FirstOrDefault().Subject.ActivityID;
                //If the activity is closed, shall the ExpertJudge be logged out automatically?
                //???????
                activities = activities.Where(a => a.ID == activityID);
                //Only activities with 'Open' status can be seen.
                activities = activities.Where(a => (ActivityStatus)a.Status == ActivityStatus.Open);
                //
                HttpContext.Session.Add("ActivityID", activityID);
                return RedirectToAction("Index", "Archive", new { activityID = activityID });
            }

            activities=activities.OrderByDescending(a => a.DueDate);
            ViewBag.PessTypeID = new SelectList(db.PessTypes, "ID", "Name");
            ViewBag.pessType = pessTypeID;
            return View(activities.ToList());
        }

        //
        // GET: /Activity/Details/5

        public ActionResult Details(int id = 0)
        {
            HttpContext.Session["ActivityID"] = id;
            Activity activity = db.Activities.Find(id);
            if (activity == null)
            {
                return HttpNotFound();
            }
            ViewData["StatusTable"] = Utility.Status(id,db);
            return View(activity);
        }
        
        //
        // GET: /Activity/Create
        [Authorize(Roles="Admin")]
        public ActionResult Create()
        {
            //ViewBag.RelatedActivityID = new SelectList(db.Activities, "ID", "Name");
            ViewBag.TypeID = new SelectList(db.PessTypes, "ID", "Name");
            ViewBag.Status = ActivityStatusList(0);
            return View();
        }

        //
        // POST: /Activity/Create

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Create(Activity activity)
        {
            if (ModelState.IsValid)
            {
                db.Activities.Add(activity);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            //ViewBag.RelatedActivityID = new SelectList(db.Activities, "ID", "Name", activity.RelatedActivityID);
            ViewBag.TypeID = new SelectList(db.PessTypes, "ID", "Name", activity.TypeID);
            ViewBag.Status = ActivityStatusList(activity.Status);
            return View(activity);
        }

        //
        // GET: /Activity/Edit/5
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id = 0)
        {
            Activity activity = db.Activities.Find(id);
            if (activity == null)
            {
                return HttpNotFound();
            }
            ViewBag.TypeID = new SelectList(db.PessTypes, "ID", "Name", activity.TypeID);
            //ActivityStatusSelectList
            ViewBag.Status = ActivityStatusList(activity.Status);
            ViewBag.HideArchiveDetails = Utility.YesNoSelectList(activity.HideArchiveDetails);

            return View(activity);
        }

        private SelectList ActivityStatusList(int? selectedStatus)
        {
            //ActivityStatusSelectList
            var activityStatusList = (from s in Utility.GetValues<ActivityStatus>()
                                      select new { ID = (int)s, Name = s.ToLocalName() }).ToList();
            return new SelectList(activityStatusList, "ID", "Name", selectedStatus);
        }
        //
        // POST: /Activity/Edit/5

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(Activity activity)
        {
            if (ModelState.IsValid)
            {
                db.Entry(activity).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", new {id=activity.ID});
            }
            //ViewBag.RelatedActivityID = new SelectList(db.Activities, "ID", "Name", activity.RelatedActivityID);
            ViewBag.TypeID = new SelectList(db.PessTypes, "ID", "Name", activity.TypeID);

            ViewBag.Status = ActivityStatusList(activity.Status);

            return View(activity);
        }

        //
        // GET: /Activity/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Activity activity = db.Activities.Find(id);
            if (activity == null)
            {
                return HttpNotFound();
            }
            return View(activity);
        }

        //
        // POST: /Activity/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Activity activity = db.Activities.Find(id);
            if (activity.Subjects.Count > 0)
            {
                ModelState.AddModelError("", "该活动中已存在学科数据，无法删除。请先删除学科，再删除活动。");
                return View(activity);
            }
            else
            {
                db.Activities.Remove(activity);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Progress(int activityID)
        {
            ActivityProgressModel model = new ActivityProgressModel();
            model.ActivityID = activityID;

            var r = db.GetActivityProgress(activityID);
            var subjectProgressModelList = from p in r
                    select new SubjectProgressModel { SubjectName = p.Name, ArchiveGradedCount = p.ArchiveGradedTotal, ArchiveTotal = p.ArchiveTotal };
            model.SubjectProgressList=subjectProgressModelList.ToList();

            return View(model);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}